package com.sxj.corejava.code18_工厂模式;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 工厂模式
 */
public class ObjectFactory {

    private static Map<String, Object> objs;

    static {
        objs = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory
                                    .class
                                    .getClassLoader()
                                    .getResourceAsStream("beans.properties")));
            String line = null;
            while ((line = br.readLine()) != null) {
                // 排除空行,排除注释
                // 以#开头的作为注释,不做解析
                if (!"".equals(line) && !line.startsWith("#")) {
                    // 将改行数据根据等号分隔
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    // 存储到集合中的value是一个具体的对象
                    // 通过反射调用对应类的构造方法获取对象
                    Class c = Class.forName(value);
                    Object obj = c.newInstance();
                    objs.put(key, obj);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getObject(String key) {
        Object obj = objs.get(key);
        if (obj == null) {
            throw new ObjectNotFoundException("根据指定的key:" + key + "在配置文件中没有找到对应的配置");
        }
        return obj;
    }

}
